<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------

namespace app\api\model;

use think\Db;
use think\Cache;
use think\Exception;
use \think\Model;
use app\api\model\Goods as G;
use app\api\controller\KbxOther;
use app\api\controller\KbxToken;
use app\api\controller\Common;

class GroupToursLine extends Model
{
    //获取列表
    public function getList($city_id=0,$page=1,$offset=10,$from='orderSystem')
    {
        $where['is_use'] = 1;
        $where['is_deleted'] = 0;
        $query_where = "";
        if($from=='wxSoft'){
            //补充筛选条件
            $keyword = $city_id;
            if(!empty($keyword)){
                $search_city = db('city')->where('name',$keyword)->find();
                if(!empty($search_city['id'])){
                    $query_where = function ($query) use ($search_city){
                        $query->where('g.city_id',$search_city['id'])->whereOr('g.title',$search_city['name']);
                    };
                }else{
                    $query_where['g.title'] = ['like','%'.$keyword.'%'];
                }
            }
        }else{
            if(!empty($city_id)){
                $where['city_id'] = $city_id;
            }
        }
        $where['is_free'] = 0;//非自由拼线路
        $total = db("group_tours_line g")->where($where)->where($query_where)->count();
        $list = db("group_tours_line g")
            ->where($where)
            ->where($query_where)
            ->join("city c",'c.id=g.city_id','left')
            ->field("g.line_id,g.title,g.img,g.sort_num,g.sold_num,
            g.show_sold,g.sold_num+g.show_sold as total_sold,
            g.hotel_unit_price,g.hotel_days,g.is_recommend,
            c.id as city_id,c.name as city_name,c.kbx_id,
            g.days,g.end_days,g.product_id,g.trip_id,g.description,
            g.from_address_json,g.to_address_json,g.carType,g.subType,
            g.toursLineTitle,g.specialInfo,g.desc,g.unitTicketPrice,
            g.carPrice,g.currency,g.currency_name,g.person_price,
            g.busy_hotel_unit_price,g.busyCarPrice,g.busy_person_price")
            ->order("g.is_recommend desc,g.sort_num desc,total_sold desc,g.line_id desc");
        if($from!="orderSystem"){
            $list = $list->page($page,$offset);
        }
        $list = $list->select();


        //关联套餐信息
        if($from=='orderSystem'){
            foreach ($list as $key=>$value){
                //增加路线信息和特殊说明
                $list[$key]['type'] = "fullday";
                $list[$key]['subType'] = $this->getSubType($value['subType']);
                //$tripData = $this->getTripData($value['trip_id']);
                //$lineSummary = $this->getTripSummary($tripData);
                //$list[$key]['toursLineTitle'] = implode("\n",$lineSummary);
                //关联的商品信息
                $list[$key]['productInfo'] = $this->getLinkGoodsInfo($value['product_id']);
                //展示出发和目的地
                $list[$key]['from'] = json_decode($value['from_address_json'],true);
                $list[$key]['to'] = json_decode($value['to_address_json'],true);
                $list[$key]['unitTicketPrice'] = [
                    "amount"=>!empty($value['unitTicketPrice'])?floatval($value['unitTicketPrice']):0,
                    "currency"=>$value['currency'],
                    "currency_name"=>$value['currency_name'],
                ];
                $list[$key]['carPrice'] = [
                    "amount"=>!empty($value['carPrice'])?floatval($value['carPrice']):0,
                    "currency"=>$value['currency'],
                    "currency_name"=>$value['currency_name'],
                ];
                $list[$key]['busyCarPrice'] = [
                    "amount"=>!empty($value['busyCarPrice'])?floatval($value['busyCarPrice']):0,
                    "currency"=>$value['currency'],
                    "currency_name"=>$value['currency_name'],
                ];
                unset($list[$key]['from_address_json'],$list[$key]['to_address_json']);
                //增加返现规则和最小最大成团人数
                $list[$key]['cashBackRules'] = $this->getCashBackRules($value['person_price'],$value['line_id']);
                $partySize = array_column($list[$key]['cashBackRules'],'people_num');
                $list[$key]['minPartySize'] = $list[$key]['maxPartySize'] = 0;
                if(!empty($partySize)){
                    $list[$key]['minPartySize'] = min($partySize);
                    $list[$key]['maxPartySize'] = max($partySize);
                }

            }
        }else{
            foreach ($list as $key=>$value){
                //临时修改销量的展示字段
                $list[$key]['sold_num'] = $list[$key]['total_sold'];
                unset($list[$key]['busy_hotel_unit_price'],$list[$key]['busyCarPrice'],$list[$key]['busy_person_price']);
            }
        }
        return [$total,$list];
    }

    //获取推荐产品的团期列表
    public function getRecGroupList()
    {
        $where['is_use'] = 1;
        $where['is_deleted'] = 0;
        $where['is_recommend'] = 1;//推荐产品的团期才生效
        $where['is_free'] = 0;//非自由拼线路
        $query_where = "";

        $list = db("group_tours_line g")
            ->where($where)
            ->where($query_where)
            ->join("city c",'c.id=g.city_id','left')
            ->field("g.line_id,g.sort_num,g.sold_num+g.show_sold as total_sold,c.id as city_id,c.name as city_name,c.kbx_id")
            ->order("g.is_recommend desc,g.sort_num desc,total_sold desc,g.line_id desc")
            ->limit(10)
            ->select();
        if(empty($list)) return [];
        $result = [];
        foreach ($list as $key=>$value){
            $groupOrder = $this->getOrderToursGroup($value['line_id']);
            if(!empty($groupOrder)){
                foreach ($groupOrder as $order_v){
                    $result[] = [
                        'time'=>$order_v['startDate'],//团期
                        'cityId'=>$value['city_id'],//城市名称
                        'cityName'=>$value['city_name'],//城市名称
                        'cityKbxId'=>$value['kbx_id'],//城市名称
//                        'title'=>$order_v['currentPartySize'].'人已拼游',//标题
                        'maxPartySize'=>$order_v['maxPartySize'],//当前团最大人数
                        'line_id'=>$value['line_id'],//当前线路ID
                        'group_id'=>$order_v['_id'],//当前团ID
                        'currentPartySize'=>$order_v['currentPartySize'],//当前参团人数
                    ];
                }
            }
            //临时修改销量的展示字段
            $list[$key]['sold_num'] = $list[$key]['total_sold'];
        }
        shuffle($result);
        return $result;
    }
    //获取详情
    public function getDetail($line_id=0,$from='orderSystem',$hasTrip=false,$cityName='')
    {
        if(empty($line_id)){
            return [];
        }else{
            $detail = db('group_tours_line g')
                ->field("g.line_id,g.title,g.img,g.sold_num,g.show_sold,
                g.sold_num+g.show_sold as total_sold,g.hotel_unit_price,g.hotel_days,
                g.is_recommend,c.id as city_id,c.name as city_name,c.kbx_id,g.days,
                g.end_days,g.product_id,g.trip_id,g.description,
                g.from_address_json,g.to_address_json,g.carType,g.subType,
                g.toursLineTitle,g.specialInfo,g.desc,g.unitTicketPrice,g.carPrice,
                g.currency,g.currency_name,g.rules,g.person_price,
                g.busy_hotel_unit_price,g.busyCarPrice,g.busy_person_price")
                ->join("city c",'c.id=g.city_id','left')
                ->where(['line_id'=>$line_id,'is_use'=>1,'is_deleted'=>0])
                ->find();
            if(empty($detail)){
                return [];
            }elseif(empty($detail['product_id'])){
                $detail['product_info'] = [];
            }else{
                $detail['person_price_currency'] = ($this->getSymbolByCurrency($detail['currency']))['currSymbol'];
                //展示出发和目的地
                $detail['from'] = json_decode($detail['from_address_json'],true);
                $detail['to'] = json_decode($detail['to_address_json'],true);
                //获取关联的商品的详情
                $product_id = $detail['product_id'];
                $detail['product_info'] = $this->getLinkGoodsInfo($product_id,$from,$cityName);
                //行程
                $detail['tripInfo'] = [];
                if(!empty($hasTrip) && !empty($detail['trip_id']) && $trip_id = $detail['trip_id']){
                    $trip = $this->getTripData($trip_id);
                    //$lineSummary = $this->getTripSummary($trip);
                    //$detail['toursLineTitle'] = implode("\n",$lineSummary);
                    //$detail['carType'] = $trip['carType']??0;
                    $detail['tripInfo'] = $trip;
                }
                $detail['subType'] = $this->getSubType($detail['subType']);
                $detail['unitTicketPrice'] = [
                    "amount"=>!empty($detail['unitTicketPrice'])?floatval($detail['unitTicketPrice']):0,
                    "currency"=>$detail['currency'],
                    "currency_name"=>$detail['currency_name'],
                ];
                $detail['carPrice'] = [
                    "amount"=>!empty($detail['carPrice'])?floatval($detail['carPrice']):0,
                    "currency"=>$detail['currency'],
                    "currency_name"=>$detail['currency_name'],
                ];
                $detail['busyCarPrice'] = [
                    "amount"=>!empty($detail['busyCarPrice'])?floatval($detail['busyCarPrice']):0,
                    "currency"=>$detail['currency'],
                    "currency_name"=>$detail['currency_name'],
                ];
                $detail['carPriceTitle'] = "包车价：".$detail['person_price_currency'].$detail['carPrice']['amount'];
                $detail['busyCarPriceTitle'] = "包车价：".$detail['person_price_currency'].$detail['busyCarPrice']['amount'];
                //临时修改销量的展示字段
                $detail['sold_num'] = $detail['total_sold'];
                return $detail;
            }
        }
    }

    //拼游规则 is_busy【是否旺季】
    public function getCashBackRules($gt_person_price,$line_id,$is_busy=false)
    {
        $cashBackRule = [];
        $package_type = $is_busy?2:1;//旺季 套餐类型为2
        $packages = db('grouptour_package')->where([
            'grouptour_id'=>$line_id,
            'package_type'=>$package_type
        ])->select();
        //没有旺季套餐 按照淡季套餐价格
        if(empty($packages)){
            $packages = db('grouptour_package')->where([
                'grouptour_id'=>$line_id,
                'package_type'=>1
            ])->select();
        }
        $package_ids = array_column($packages,'id');
        if(empty($package_ids)) return $cashBackRule;
        $specs = db('grouptour_specs')->where(['package_id'=>['in',$package_ids]])->select();
        if(empty($specs)) return $cashBackRule;

        foreach ($specs as $value){
            $cashBackValue = $gt_person_price - $value['price'];
            $cashBackRule[$value['num']] = $cashBackValue<0?0:$cashBackValue;
        }
        foreach ($cashBackRule as $key=>$value){
            $cashBackRules[] = ['people_num'=>$key,'cashBack'=>$value,'title'=>$key.'人成行','ruleName'=>'返现$'.$value.'/人'];
        }
        return $cashBackRules;
    }
    //获取商品套餐信息
    private function getLinkGoodsInfo($goods_id=0,$from="orderSystem",$cityName='')
    {
        if($from=="orderSystem"){
            $field = "goods_id,goods_name,need_confirm,city_id,goodssales,invented_sold";
        }else{
            $field = "goods_id,goods_name,orderType,goods_introduce,
            goods_enintroduce,goods_usetime,price_include,price_noinclude,
            goods_careful,goods_retreating,goods_status,goods_image,
            goods_englishname,need_confirm,city_id,goods_video,goodssales,invented_sold";
        }
        $product = db("goods")
            ->field($field)
            ->find($goods_id);
        if(empty($product)){
            return [];
        }else {
            //获取货币单位
            if(!empty($cityName)){
                $city = db('city')->where('name',$cityName)->find();
                $product['city_id'] = $city['id']??$product['city_id'];
            }
            if(!empty($product['invented_sold'])){
                $product['goodssales'] += $product['invented_sold'];
            }
            //获取美元价货币单位
            $product['currency'] = (new G())->getCurrencyByCityId($product['city_id']);
            $exchange_rate = (new G())->getExchangerateByCityId($product['city_id']);
            $product['exchange_rate'] = $exchange_rate;
            $max = $min = $foreign_max = $foreign_min =0;
            unset($product['city_id']);
            $person = [];
            if($from!='wxSoft'){
                //获取套餐价格
                $spec_where['goods_id'] = $goods_id;
                $spec_where['specs_status'] = 1;
                $specs = db("specs")->where($spec_where)->select();
                if (!empty($specs) && $specs_id = array_column($specs, "specs_id")) {
                    $person_where['p.specs_id'] = ['in', $specs_id];
                    $person_where['person_status'] = 1;
                    $person = db("person p")
                        ->join("specs s", 'p.specs_id=s.specs_id', 'left')
                        ->field("s.specs_id,s.specs_name,p.person_id,p.person_name,p.person_num,p.person_price,p.minorder_num,p.inc_order_num")
                        ->where($person_where)
                        ->select();
                    foreach ($person as $pk=>$pv){
                        //增加每个套餐的总价
                        $person[$pk]['total_price'] = $pv['person_price']*$pv['person_num'];
                        $person[$pk]['foreign_person_price'] = sprintf('%.2f',$pv['person_price']/$exchange_rate);
                    }
                } else {
                    $person = [];
                }
                //$product['person'] = $person;
                //$person_price = array_column($person,'person_price');
            }

            if(!empty($person_price)){
                $max = max($person_price);
                $min = min($person_price);
                $foreign_min = sprintf('%.2f',$min/$exchange_rate);
                $foreign_max = sprintf('%.2f',$max/$exchange_rate);
                if($min==$max){
                    $product['price_section'] = $min;
                    $product['foreign_price_section'] = $foreign_min;
                }else{
                    $product['price_section'] = $min.'~'.$max;
                    $product['foreign_price_section'] = $foreign_min.'~'.$foreign_max;
                }
            }else{
                $product['price_section'] ='';
                $product['foreign_price_section'] = '';
            }
            return $product;
        }
    }

    public function getTripData($trip_id=0,$from='orderSystem')
    {
        if(empty($trip_id)){
            return [];
        }else{
            $trip = db("product")
                ->field("id,price,start_city,name,title,description,content,comment,introduction,days,careful,back,priceno,carType")
                ->find($trip_id);
            if(empty($trip)){
                return [];
            }
            $schedule = db("pschedule")
                ->where(['groupid'=>$trip_id])
                ->field('id,time,name,title,displayorder')
                ->order("displayorder asc")
                ->select();
        }
        if(!empty($schedule) && $schedule_ids = array_column($schedule,'id')){
            $active = db("pactive a")
                ->join("poi p",'p.id=a.poiid','left')
                ->where(['a.groupid'=>['in',$schedule_ids]])
                ->field("a.activeType,a.title,a.content,a.poiid,a.poiname,a.poi_content,p.name as p_name,p.eng_name as p_ename,p.lat,p.lng,p.typeid,a.groupid")
                ->order("a.displayorder asc")
                ->select();
            foreach ($schedule as $s_key=>$s_value){
                $schedule[$s_key]['child'] = [];
                foreach ($active as $a_key=>$a_value){
                    if($a_value['groupid']==$s_value['id']){
                        $a_value['typeid_name'] = $this->getTypeName($a_value['typeid']);
                        $schedule[$s_key]['child'][] = $a_value;
                        unset($active[$a_key]);
                    }
                }
            }
        }
        $trip['child'] = $schedule;
        //设置商品缓存信息
        //Cache::tag('toursline_trip')->set($from.'_toursline_trip_'.$trip_id,$trip,2*3600);
        return $trip;
    }

    //获取日程的poi数据
    public function getProductSchedules($trip_id=0,$from='orderSystem')
    {
        if(empty($trip_id)){
            return [];
        }else{
            $trip = db("product")
                ->field("id,price,start_city,name,title,description,content,comment,introduction,days,careful,back,priceno,carType")
                ->find($trip_id);
            if(empty($trip)){
                return [];
            }
            $schedule = db("pschedule")
                ->where(['groupid'=>$trip_id])
                ->field('id,time,name,title,displayorder')
                ->order("displayorder asc")
                ->select();
        }
        $trip['tripDestination'] = [];
        if(!empty($schedule) && $schedule_ids = array_column($schedule,'id')){
            $active = db("pactive a")
                ->join("pschedule ps",'ps.id=a.groupid','left')
                ->join("poi p",'p.id=a.poiid','left')
                ->where(['a.groupid'=>['in',$schedule_ids]])
                ->field("a.activeType,a.title,a.content,a.poiid,a.poiname,
                    a.poi_content,p.name as p_name,p.eng_name as p_ename,
                    p.lat,p.lng,p.typeid,a.groupid,p.groupid as city_id,
                    a.poiImg,a.other_images,a.time as arrivalTime")
                ->order("ps.displayorder asc,a.displayorder asc")
                ->select();
            $trip['tripDestination'] = $this->getCitiesByTripData($active);
            foreach ($schedule as $s_key=>$s_value){
                $schedule[$s_key]['child'] = [];
                foreach ($active as $a_key=>$a_value){
                    if($a_value['groupid']==$s_value['id']){
                        $a_value['typeid_name'] = $this->getTypeName($a_value['typeid']);
                        $a_value['images'] = $a_value['poiImg'].','.$a_value['other_images'];
                        $a_value['images'] = array_values(array_filter(explode(',',$a_value['images'])));
                        unset($a_value['poiImg'],$a_value['other_images']);
                        $schedule[$s_key]['child'][] = $a_value;
                        unset($active[$a_key]);
                    }
                }
            }
        }
        $trip['child'] = $schedule;
        //设置商品缓存信息
        //Cache::tag('toursline_trip')->set($from.'_toursline_trip_'.$trip_id,$trip,2*3600);
        return $trip;
    }

    //获取线路沿途的城市
    public function getCitiesByTripData($activeData)
    {
        $citys = [];
        $city_ids = [];
        if(empty($activeData)) return $citys;
        foreach ($activeData as $value){
            if(!empty($value['city_id']) && end($city_ids) != $value['city_id']){
                $city_ids[] = $value['city_id'];
            }
        }
        if(!empty($city_ids)){
            $cityData = db('city')->field('id,name,eng_name')->where(['id'=>['in',$city_ids]])->select();
            foreach ($city_ids as $value){
                foreach ($cityData as $city_value){
                    if($city_value['id']==$value){
                        $citys[] = $city_value;break;
                    }
                }
            }
        }
        return $citys;
    }
    /**
     * 获取定制产品的行程名称
     * @param array $tripData 行程数据
     * @return array 行程的每日路线
     */
    public function getTripSummary($tripData)
    {
        if(empty($tripData) || !isset($tripData['child']) || empty($tripData['child'])){
            return [];
        }else{
            $summary = [];
            if(count($tripData['child'])==1
                && empty($tripData['child'][0]['child'][0]['poiname'])
                && empty($tripData['child'][0]['child'][0]['title'])
            ){
                return $summary;//节点中并没有实质的内容
            }
            foreach ($tripData['child'] as $key=>$value){
                $string = "第".$value['displayorder'].'天:';
                $dayTitle = [];
                if(isset($value['child']) && !empty($value['child'])){
                    foreach ($value['child'] as $kk=>$vv){
                        $dayTitle[] = !empty($vv['poiname'])?$vv['poiname']:$vv['title'];
                    }
                }else{
                    continue;
                }
                $dayTitle = array_filter($dayTitle);
                if(empty($dayTitle)){
                    continue;
                }
                $dayTitleStr = implode("--",$dayTitle);
                $summary[] = $string.$dayTitleStr;
            }
            return $summary;
        }
    }
    //获取poitype名称
    //1景点，2体验项目，3演出赛事，4限时活动，5酒店，6其他，7机场，8供应商，
    //11美食，12停车场，13加油站，14购物，15租车
    public function getTypeName($typeid)
    {
        switch ($typeid){
            case 1:
                return "景点";break;
            case 2:
                return "体验项目";break;
            case 3:
                return "演出赛事";break;
            case 4:
                return "限时活动";break;
            case 5:
                return "酒店";break;
            case 6:
                return "其他";break;
            case 7:
                return "机场";break;
            case 8:
                return "供应商";break;
            case 9:
                return "";break;
            case 10:
                return "";break;
            case 11:
                return "美食";break;
            case 12:
                return "停车场";break;
            case 13:
                return "加油站";break;
            case 14:
                return "购物";break;
            case 15:
                return "租车";break;
            default:
                return "";break;

        }
    }
    /**
     * 根据标签清除关联的缓存
     * @param string $type 标签
     */
    public function clearLinkCache($tag){
        Cache::clear($tag);
    }

    public function getOrderToursGroup($line_id=0)
    {
        if(empty($line_id)){
            return [];
        }
        $kbxToken = new KbxToken();
        $url = $kbxToken->url.'/carpool/listCarPoolOrdersByLine?line='.$line_id;
        $token = 'Bearer ' . $kbxToken->kbxToken();
        $res = $kbxToken->get_data($url, $token);
        $data = $kbxToken->object_array($res);
//        $data = [];
        $orderData = [];
        if(!empty($data)){
            foreach ($data as $key=>$value){
                $startDate = $value['details']['startDate']??"";
                $startDateTitle = empty($startDate)?"":date("m月d日",strtotime($startDate));
                $value['startDate'] = $startDate;
                $value['startDateTitle'] = $startDateTitle;
                $value['title'] = $this->getCarPoolOrdersTitle($value);
                $orderData[] = $value;
                //数据过滤 暂不启用 2019 06 24 byMax
//                $orderData[] = [
//                    "_id"=>$value['_id']??"",
//                    "name"=>$value['name']??"",
//                    "startDate"=>$startDate,
//                    "startDateTitle"=>$startDateTitle,
//                    "line"=>$value['line']??"",
//                    "maxPartySize"=>$value['maxPartySize']??"",
//                    "payDeadline"=>$value['payDeadline']??"",
//                    "orderId"=>$value['orderId']??"",
//                    "price"=>$value['price']??[],
//                    "status"=>$value['status']??"",
//                    "unpaidCustomers"=>$value['unpaidCustomers']??[],
//                    "customers"=>$value['customers']??[],
//                    "details"=>$value['details']??[],
//                ];
            }
        }else{
            //模拟数据
//            $sday = 7;
//            $eday = 10;
//            $startDate = date("Y-m-d",strtotime("+ $sday day"));
//            $startDateTitle = date("m月d日",strtotime("+ $sday day"));
//            $endDate = date("Y-m-d",strtotime("+ $eday day"));
//            $orderData[] = [
//                "_id"=>"",
//                "name"=>"模拟数据",
//                "startDate"=>$startDate,
//                "startDateTitle"=>$startDateTitle,
//                "line"=>$line_id,
//                "maxPartySize"=>"8",
//                "payDeadline"=>$endDate,
//                "orderId"=>"",
//                "price"=>[],
//                "status"=>"open",
//                "unpaidCustomers"=>[],
//                "customers"=>[],
//                "details"=>[],
//            ];
        }
        return $orderData;
    }
    //获取当前拼团的标题【已满员/2人成行剩3人】
    protected function getCarPoolOrdersTitle($order){
        if(empty($order) || empty($order['maxPartySize'])) return '';
        if(empty($order['currentPartySize'])) return '0人已报名/剩'.$order['maxPartySize'].'人';
        if($order['maxPartySize'] <= $order['currentPartySize']) return '已满员';
        return $order['currentPartySize'].'人已报名/剩'.($order['maxPartySize']-$order['currentPartySize']).'人';
    }
    //获取推荐的线路列表
    public function recommendGroupTours()
    {
        $where['is_use'] = 1;
        $where['is_deleted'] = 0;
        $where['is_recommend'] = 1;
        $where['is_free'] = 0;//非自由拼线路

        $field = "g.line_id,g.title,g.img,g.sort_num,g.sold_num,g.show_sold,g.sold_num+g.show_sold as total_sold,g.hotel_unit_price,g.hotel_days,g.is_recommend,c.id as city_id,c.name as city_name,c.kbx_id,g.days,g.end_days,g.product_id,g.trip_id,g.description,g.from_address_json,g.to_address_json,g.carType,g.subType,g.toursLineTitle,g.specialInfo,g.desc,g.unitTicketPrice,g.carPrice,g.currency,g.currency_name,g.person_price";
        $list = db("group_tours_line g")->where($where)
            ->join("city c",'c.id=g.city_id','left')
            ->field($field)
            ->order("g.is_recommend desc,g.sort_num desc,total_sold desc,g.line_id desc")
            ->limit(1)
            ->select();
        if(empty($list)){
            unset($where['is_recommend']);
            $list = db("group_tours_line g")->where($where)
                ->join("city c",'c.id=g.city_id','left')
                ->field($field)
                ->order("g.sort_num desc,total_sold desc,g.line_id desc")
                ->limit(1)
                ->select();
        }
        return $list;
    }

    public function getSubType($subType=0)
    {
        $title = "";
        switch ($subType){
            case 1:
                $title = "halfday";
                break;
            case 2:
                $title = "oneday";
                break;
            case 3:
                $title = "around";
                break;
            case 4:
                $title = "longtrip";
                break;
            default:
                $title = "";
                break;
        }

        return $title;
    }

    //通过日期和商品id获取套餐价格
    public function getGoodsSpecPriceByDate($goods_id,$date)
    {
        $priceList = [];
        $goodsinfo = db("goods")->find($goods_id);
        if(!empty($goodsinfo)){
            $specs = db("specs")->where(['goods_id'=>$goods_id])->select();
            if(!empty($specs)){
                $specs_id = array_column($specs,"specs_id");
                $persons = db("person")->where(['specs_id'=>['in',$specs_id]])->select();
                if(!empty($persons)){
                    $persons_id = array_column($persons,"person_id");
                    $priceList = db("personday p")
                        ->field('p.person_id,p.person_name,p.person_num,p.person_price,p.minorder_num,p.inc_order_num')
                        ->where(['p.person_id'=>['in',$persons_id],'time'=>$date])
                        ->select();
                    foreach ($priceList as $key=>$value){
                        $priceList[$key]['total_price'] = $value['person_num']*$value['person_price'];
                    }
                }
            }
        }
        return $priceList;
    }

    /**
     * 获取酒店房价配置
     */
    public function getRoomPrice($line_id=0)
    {
        $field = "room_id,room_name,room_price,room_person_num";
        $price = db("standard_hotel_config")
            ->field($field)
            ->where(['link_id'=>$line_id])
            ->order("sort_num desc")
            ->select();

        return $price;
    }

    //获取套餐配置
    public function getPackageSpecByLineId($line_id,$exchange_rate=1,$is_busy=false)
    {
        if(empty($line_id)) return [];
        $package_type = $is_busy?2:1;
        $packages = db('grouptour_package')
            ->where(['grouptour_id'=>$line_id,'package_type'=>$package_type])
            ->field('id,name')
            ->select();
        if(empty($packages)) return [];
        foreach ($packages as $key=>$value){
            $specs = db('grouptour_specs')
                ->field('id,name,price,num,minorder_num,inc_order_num')
                ->where('package_id',$value['id'])
                ->select();
            foreach ($specs as $k=>$v){
                $specs[$k]['price_cny'] = sprintf('%.2f',$v['price']*$exchange_rate);
            }
            $packages[$key]['child'] = $specs;
        }
        return $packages;
    }

    //是否主动生成套餐数据
    public function autoCreateSpecsByLineId($line_id)
    {
        $line = db('group_tours_line')->find($line_id);
        if(empty($line_id) || empty($line)) return "线路不存在";
        //已经自动生成过套餐
        if($line['auto_spec_flag'] > 0) return [];
        return $this->createSpecsByLineId($line);
    }
    //生成淡旺季套餐数据
    public function createSpecsByLineId($line)
    {
        if(empty($line['person_price'])) return "请先配置单人售价";
        if(empty($line['carPrice'])) return "请先配置派单价";//七座车派单价
        if(empty($line['busy_person_price'])) return "请先配置（旺季）单人售价";
        if(empty($line['busyCarPrice'])) return "请先配置（旺季）派单价";//七座车派单价
        //如果存在套餐直接返回
        $exist_package = db('grouptour_package')->where('grouptour_id',$line['line_id'])->find();
        if(!empty($exist_package)) return "套餐已存在，请勿再次生成";
        //单人售价规则
        // 1-3 七座车派单价 $line['carPrice']*比例（配置项） 派单价*1.05/2
        // 4-5 七座车派单价 $line['carPrice']*比例（配置项） 派单价*1.05/2
        //淡季成本
        $lessPeopleCarPrice = ceil($line['carPrice']/config('lessPeopleSpecsAddRate'));
        $morePeopleCarPrice = ceil($line['carPrice']/config('morePeopleSpecsAddRate'));
        $unitSalePrice = $line['person_price'];
        //旺季成本
        $unitBusySalePrice = $line['busy_person_price'];
        db::startTrans();
        try{
            //淡季套餐设置
            $package_id = db('grouptour_package')->insertGetId([
                'grouptour_id'=>$line['line_id'],
                'name'=>'淡季套餐',
                'creattime'=>time(),
                'updatetime'=>time(),
                'package_type'=>1//淡季
            ]);
            $cashBackList = [];
            for($i=1;$i<=5;$i++){
                if($i<3){
                    $cashBack = 0;
                }elseif($i==3){
                    $cashBack = intval((($unitSalePrice*$i)-$lessPeopleCarPrice)*0.1);
                }else{
                    $cashBack = intval((($unitSalePrice*$i)-$morePeopleCarPrice)*0.1);
                }
                $price = $unitSalePrice - $cashBack;
                db('grouptour_specs')->insert([
                    'name'=>$i.'人成行',
                    'package_id'=>$package_id,
                    'num'=>$i,
                    'minorder_num'=>$i,
                    'inc_order_num'=>1,
                    'creattime'=>time(),
                    'updatetime'=>time(),
                    'price'=>$price
                ]);
                $cashBackList[$i] = $cashBack;
            }
            //旺季套餐设置
            $busy_package_id = db('grouptour_package')->insertGetId([
                'grouptour_id'=>$line['line_id'],
                'name'=>'旺季套餐',
                'creattime'=>time(),
                'updatetime'=>time(),
                'package_type'=>2//旺季
            ]);
            for($i=1;$i<=5;$i++){
                $cashBack = $cashBackList[$i];
                $price = $unitBusySalePrice - $cashBack;
                db('grouptour_specs')->insert([
                    'name'=>$i.'人成行',
                    'package_id'=>$busy_package_id,
                    'num'=>$i,
                    'minorder_num'=>$i,
                    'inc_order_num'=>1,
                    'creattime'=>time(),
                    'updatetime'=>time(),
                    'price'=>$price
                ]);
            }
            //修改已自动生成套餐的标识
            db('group_tours_line')->where('line_id',$line['line_id'])->update([
                'auto_spec_flag'=>1
            ]);
            db::commit();
            return ['msg'=>'success'];
        }catch(Exception $e){
            db::rollback();
            return $e->getMessage();
        }
    }
    //生成旺季套餐数据 【按照淡季套餐的返现规则生成】
    public function createBusySpecsByLineId($line)
    {
        if(empty($line['person_price'])) return "请先配置单人售价";
        if(empty($line['carPrice'])) return "请先配置派单价";//七座车派单价
        if(empty($line['busy_person_price'])) return "请先配置（旺季）单人售价";
        if(empty($line['busyCarPrice'])) return "请先配置（旺季）派单价";//七座车派单价
        //如果存在套餐直接返回
        $exist_package = db('grouptour_package')->where(['grouptour_id'=>$line['line_id'],'package_type'=>1])->find();
        if(empty($exist_package)) return "淡季套餐不存在，请创建淡旺季套餐";
        $exist_busy_package = db('grouptour_package')->where(['grouptour_id'=>$line['line_id'],'package_type'=>2])->find();
        if(!empty($exist_busy_package)) return "旺季套餐已存在，请勿再次生成";
        //单人售价规则
        // 1-3 七座车派单价 $line['carPrice']*比例（配置项） 派单价*1.05/2
        // 4-5 七座车派单价 $line['carPrice']*比例（配置项） 派单价*1.05/2
        //淡季成本
        $specs = db('grouptour_specs')->where('package_id',$exist_package['id'])->select();
        //旺季成本
        $unitSalePrice = $line['person_price'];
        $unitBusySalePrice = $line['busy_person_price'];
        db::startTrans();
        try{
            //淡季套餐设置
            $package_id = db('grouptour_package')->insertGetId([
                'grouptour_id'=>$line['line_id'],
                'name'=>'旺季套餐',
                'creattime'=>time(),
                'updatetime'=>time(),
                'package_type'=>2//旺季
            ]);
            foreach ($specs as $key=>$value){
                $cashBack = $unitSalePrice - $value['price'];
                $price = $unitBusySalePrice - $cashBack;
                db('grouptour_specs')->insert([
                    'name'=>$value['num'].'人成行',
                    'package_id'=>$package_id,
                    'num'=>$value['num'],
                    'minorder_num'=>$value['num'],
                    'inc_order_num'=>1,
                    'creattime'=>time(),
                    'updatetime'=>time(),
                    'price'=>$price
                ]);
            }
            db::commit();
            return ['msg'=>'success'];
        }catch(Exception $e){
            db::rollback();
            return $e->getMessage();
        }
    }
    //通过币种获取符号
    public function getSymbolByCurrency($currency_code='CNY')
    {
        $currencySet = [];
        $currencyList = (new Common())->getCurrencyListByCity();
        foreach ( $currencyList as $currency_v){
            $currencySet[$currency_v['currency_code']] = [
                'currSymbol'=>$currency_v['currency_symbol'],
                'currName'=>$currency_v['currency_name'],
            ];
        }

        return $currencySet[$currency_code]??$currencySet['CNY'];
    }

    //图片域名地址替换
    public function replaceOssImgDomain($str)
    {
        $search_str = "kwibon-public-images.oss-cn-beijing.aliyuncs.com";
        $replace_str = "i.kuaibangxing.com";
        return str_replace($search_str,$replace_str,$str);
    }
}